package xiaojian.toolkit.netty.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class IntegerUUID {
    public static AtomicInteger uuid = new AtomicInteger();

    public static int nextUUID(){
        return uuid.incrementAndGet();
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        int threads = 10;
        ExecutorService workers = Executors.newFixedThreadPool(threads);
        CompletionService service = new ExecutorCompletionService(workers);
        long start = System.currentTimeMillis();
        final List list = new ArrayList();

        for(int i = 0;i<threads;i++){
            service.submit(new Callable() {
                public Object call() {
                    long begin = System.currentTimeMillis();
                    int id = IntegerUUID.nextUUID();
                    while (id < 10000){
                        if(list.contains(id)){
                            throw new RuntimeException("not thread safe!");
                        }
                        list.add(id);
                        id = IntegerUUID.nextUUID();
                    }
                    return System.currentTimeMillis() - begin;
                }
            });
        }

        for(int i = 0;i<threads;i++){
            service.take().get();
        }
        System.out.println(System.currentTimeMillis()-start);
        workers.shutdown();
    }
}
